package class01.test;

import java.util.Arrays;
import java.util.Random;

public class Code05_BSNearLeft {
    public static int nearestIndex(int[] arr, int num){
        if(arr == null || arr.length == 0){
            return -1;
        }
        if(arr[arr.length - 1] < num){
            return -1;
        }
        int L = 0;
        int R = arr.length;
        int mid = 0;
        int index = -1;
        while (L <= R){
            mid = L + ((R - L)>>1);
            if(arr[mid] >= num){
                index = mid;
                R = mid - 1;
            }else {
                L = mid + 1;
            }
        }
        return index;

    }

    public static void main(String[] args) {
        int testTime = 5000000;
        int maxSize = 100;
        int maxValue = 100;
        boolean succeed = true;
        for (int i = 0; i < testTime; i++) {
            int[] arr = generateRandomArray(maxSize,maxValue);
            Arrays.sort(arr);
            int num = ((int)((maxValue + 1)* Math.random()));
            if(nearestIndex(arr,num) != test(arr,num)){
                System.out.println(num);
                printArray(arr);
                succeed =false;
                break;
            }

        }
        System.out.println(succeed?"good":"bad");
    }

    private static int test(int[] arr, int num) {
        if(arr == null || arr.length ==0){
            return -1;
        }
        for (int i = 0; i < arr.length; i++) {
            if(arr[i] >= num){
                return i;
            }

        }
        return -1;
    }

    private static void printArray(int[] arr) {
        if(arr == null || arr.length == 0){
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    private static int[] generateRandomArray(int maxSize, int maxValue) {
        int[] arr = new int[((int)((maxSize+1) * Math.random()))];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = ((int)((maxValue+ 1) * Math.random())) - ((int)((maxValue) * Math.random()));
        }
        return arr;
    }
}
